<template>
  <div v-if="!record || !record.contact">
    <LoadingSpinner :prompt="'Loading record...'"></LoadingSpinner>
  </div>
  <div v-else class="record">
    <div class="headline-container">
      <Photo v-bind:photo="record.photo" class="headline-item"></Photo>
      <div class="headline-item">
        <h1>
          <span>Record: {{ record.contact.fullName }}</span>
        </h1>
        <p>
          {{ record.contact.badgeId }} &bull; {{ record.contact.email }}
          <span v-if="altSystemDeeplink"
            >&bull;
            <a
              :href="altSystemDeeplink"
              target="_blank"
              rel="noopener noreferrer"
              >{{ config.deeplink }}</a
            ></span
          >
        </p>
      </div>
    </div>

    <History v-bind:history="record.history"></History>

    <ul class="nav nav-tabs">
      <li id="tab_mode_record_details">
        <a @click="updateMode(modeDetails)">Details</a>
      </li>
      <li v-if="record.history" id="tab_mode_record_history">
        <a @click="updateMode(modeEntry)">Entry</a>
      </li>
      <li id="tab_mode_record_files">
        <a @click="updateMode(modeFiles)">Files</a>
      </li>
      <li
        v-show="numTeams > 0 && enableFollowup"
        id="tab_mode_record_create_appointment"
      >
        <a @click="updateMode(modeCreateAppointment)">Create Appointment</a>
      </li>
    </ul>

    <div v-if="mode === modeDetails">
      <RecordDetails v-bind:record="record"></RecordDetails>
    </div>

    <div v-else-if="mode === modeEntry">
      <Entry
        v-if="id && entry_id && entry"
        v-bind:entry="entry"
        v-bind:holds="record.holds"
        v-bind:readonly="readonly"
        v-bind:record_id="id"
      ></Entry>
      <LoadingSpinner
        v-else-if="id && entry_id"
        :prompt="'Loading entry...'"
      ></LoadingSpinner>
      <p v-else>Choose an Entry from the table to view more details.</p>
    </div>

    <div v-else-if="mode === modeFiles">
      <Files v-bind:files="record.files"></Files>
    </div>

    <div v-else-if="mode === modeCreateAppointment">
      <Followup v-bind:id="record.contact.id"></Followup>
    </div>

    <div v-else>Unknown mode: {{ mode }}</div>
  </div>
</template>

<script>
import RecordDetails from "@/components/RecordDetails.vue";
import Entry from "@/components/Entry.vue";
import Files from "@/components/Files.vue";
import Followup from "@/components/Followup.vue";
import History from "@/components/History.vue";
import LoadingSpinner from "@/components/LoadingSpinner.vue";
import Photo from "@/components/Photo.vue";
import { mapMutations, mapGetters } from "vuex";

export default {
  name: "Record",
  components: {
    RecordDetails,
    Entry,
    Files,
    Followup,
    History,
    LoadingSpinner,
    Photo
  },
  props: ["id", "entry_id"],
  computed: {
    ...mapGetters(["api", "readonly", "config", "enableFollowup"]),
    entry: function() {
      return this.runtimevals.entry;
    },
    record: function() {
      return this.runtimevals.record;
    },
    altSystemDeeplink: function() {
      return this.record.deeplink ? this.record.deeplink : "";
    },
    modesAvailable: function() {
      return [
        this.modeDetails,
        this.modeEntry,
        this.modeFiles,
        this.modeCreateAppointment
      ];
    },
    modeDetails: function() {
      return "mode_record_details";
    },
    modeEntry: function() {
      return "mode_record_entry";
    },
    modeFiles: function() {
      return "mode_record_files";
    },
    modeCreateAppointment: function() {
      return "mode_record_create_appointment";
    }
  },
  data() {
    return {
      mode: "mode_record_details",
      numTeams: 1,
      loading: false,
      runtimevals: {
        record: "",
        entry: ""
      },
      errorPrompt: ""
    };
  },
  methods: {
    ...mapMutations(["updateErrorPrompt"]),
    updateMode: function(mode) {
      this.mode = mode;
    },
    getRecord: function() {
      function getData(endpoint, that, bucket, refs, errorPrompt) {
        that["loading"] = true;
        if (endpoint) {
          fetch(`${endpoint}?id=${that.id}`)
            .then(response => response.json())
            .then(json => {
              if (json) {
                that[bucket][refs] = json;
                that["loading"] = false;
              } else {
                that[errorPrompt] = "Response failed.";
                that["loading"] = false;
              }
            })
            .catch(error => {
              that[errorPrompt] = `Request failed. ${error}`;
              that["loading"] = false;
            });
        } else {
          that[errorPrompt] = "No configuration.";
          that["loading"] = false;
        }
      }

      getData(this.api.record, this, "runtimevals", "record", "errorPrompt");
    },
    getEntry: function() {
      function getData(endpoint, that, bucket, refs, errorPrompt) {
        that["loading"] = true;
        if (endpoint) {
          fetch(`${endpoint}?id=${that.entry_id}`)
            .then(response => response.json())
            .then(json => {
              if (json) {
                that[bucket][refs] = json;
                that["loading"] = false;
              } else {
                that[errorPrompt] = "Response failed.";
                that["loading"] = false;
              }
            })
            .catch(error => {
              that[errorPrompt] = `Request failed. ${error}`;
              that["loading"] = false;
            });
        } else {
          that[errorPrompt] = "No configuration.";
          that["loading"] = false;
        }
      }

      getData(this.api.entry, this, "runtimevals", "entry", "errorPrompt");
    }
  },
  mounted() {
    this.getRecord();
    if (this.entry_id) {
      this.updateMode(this.modeEntry);
      this.getEntry();
    }
  },
  watch: {
    entry_id() {
      this.runtimevals.entry = "";
      this.updateMode(this.modeEntry);
      this.getEntry();
    }
  }
};
</script>

<style scoped>
.headline-container {
  display: flex;
  flex-wrap: wrap;
}

.headline-item {
  padding-right: 2%;
}

.headline-item:last-of-type {
  min-width: 50%;
}
</style>
